//
//  HNHHEQVisualizer.m
//  HNHH
//
//  Created by Dobango on 9/17/13.
//  Copyright (c) 2013 RC. All rights reserved.
//

#import "PCSEQVisualizer.h"
#import "UIImage+Color.h"

#define kWidth 8
#define kHeight 35
#define kPadding 3

@interface PCSEQVisualizer ()



@property (nonatomic, assign) CGFloat barWidth;
@property (nonatomic, assign) CGFloat barHeight;
@property (nonatomic, assign) int numberOfBars;
@property (nonatomic, assign) CGFloat barPadding;

@end

@implementation PCSEQVisualizer
{
    NSTimer* timer;
    NSArray* barArray;
}

- (instancetype)initWithNumberOfBars:(int)numberOfBars barColor:(UIColor *)barColor barWidth:(CGFloat)barWidth barHeight:(CGFloat)barHeight barPadding:(CGFloat)padding{
    self = [self initWithFrame:CGRectZero];
    if (self) {
        
        _numberOfBars = numberOfBars;
        _barWidth = barWidth;
        _barHeight = barHeight;
        
        _barPadding = padding;
        
        _barColor = barColor;
        
        self.frame = CGRectMake(5,5 , _barPadding*_numberOfBars+(_barWidth*_numberOfBars), _barHeight);
        
        NSMutableArray* tempBarArray = [[NSMutableArray alloc]initWithCapacity:_numberOfBars];
        
        for(int i=0;i<numberOfBars;i++){
            
            UIImageView* bar = [[UIImageView alloc]initWithFrame:CGRectMake(i*_barWidth+i*_barPadding, 0, _barWidth, 1)];
            bar.image = [UIImage imageWithColor:_barColor];
            [self addSubview:bar];
            [tempBarArray addObject:bar];
            
        }
        
        barArray = [[NSArray alloc]initWithArray:tempBarArray];
        
        CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI_2*2);
        self.transform = transform;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stop) name:@"kPCSEQStopTimerNotification" object:nil];
        
    }
    return self;
}

- (id)initWithNumberOfBars:(int)numberOfBars
{
    self = [self initWithNumberOfBars:numberOfBars barColor:[UIColor whiteColor] barWidth:kWidth barHeight:kHeight barPadding:kPadding];
    if (self) {
        
    }
    return self;
}


-(void)start{
    if (timer) {
        return;
    }
    self.hidden = NO;
    timer = [NSTimer scheduledTimerWithTimeInterval:.2 target:self selector:@selector(ticker) userInfo:nil repeats:YES];
    
    // fire while tracking touches
    [[NSRunLoop mainRunLoop] addTimer: timer
                              forMode: UITrackingRunLoopMode];

}


-(void)stop{
    
    [timer invalidate];
    timer = nil;
    
}

-(void)ticker{

    [UIView animateWithDuration:.35 animations:^{
        
        for(UIImageView* bar in barArray){
            
            CGRect rect = bar.frame;
            rect.size.height = arc4random() % (NSInteger)(self.barHeight) + 1;
            bar.frame = rect;
            
            
        }
    
    }];
}

@end
